package io.github.cubelitblade.librarymanagementbackend.controller;

import io.github.cubelitblade.librarymanagementbackend.dto.UserDTO;
import io.github.cubelitblade.librarymanagementbackend.exception.BusinessException;
import io.github.cubelitblade.librarymanagementbackend.service.AuthService;
import io.github.cubelitblade.librarymanagementbackend.utils.ResultContext;
import io.github.cubelitblade.librarymanagementbackend.vo.UserVO;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.net.URI;
import java.net.URISyntaxException;

@RestController
@RequestMapping("/api/auth")
public class AuthController {
    private final AuthService authService;

    public AuthController(AuthService authService) {
        this.authService = authService;
    }

    @PostMapping("/register")
    public ResponseEntity<ResultContext<UserVO>> register(@RequestBody UserDTO userDTO) {
        try {
            UserVO userVO = authService.register(userDTO);
            return ResponseEntity
                    .created(new URI("http://localhost:8080/api/users/{id}"
                            .replace("{id}", userVO.getId().toString())))
                    .body(ResultContext.succeed(userVO));
        } catch (URISyntaxException e) {
            throw BusinessException.businessFailure();
        }
    }

    @PostMapping("/login")
    public ResponseEntity<ResultContext<UserVO>> login(@RequestBody UserDTO userDTO) {
        return ResponseEntity.ok(ResultContext.succeed(authService.login(userDTO)));
    }

    @GetMapping("/heartbeat/{id}")
    public ResponseEntity<ResultContext<UserVO>> checkSession(@PathVariable Integer id) {
        return ResponseEntity.ok(ResultContext.succeed(authService.checkSession(id)));
    }
}
